package com.mryang.hds.configs;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mryang.hds.utils.JWTUtil;
import com.mryang.hds.utils.ResultCode;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


/**
 * @author Genius
 * @version 1.0.0
 * @ClassName TokenInterceptor.java
 * @Description TODO Token验证-拦截器
 * @createTime 2022年12月25日 19:40:00
 */


public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String token = request.getHeader("token");


        boolean verify = JWTUtil.verify(token);

        if (!verify){
            //向客户端做出响应
            // PrintWriter printWriter = response.getWriter();
            // Map<String,Object> map = new HashMap<>();
            //
            // map.put("code",202);
            // map.put("message","登录失效!");
            // //转为json向前端响应
            // ObjectMapper objectMapper = new ObjectMapper();
            // printWriter.print(objectMapper.writeValueAsString(map));
            // //将输出流释放,关闭
            // printWriter.flush();
            // printWriter.close();

            throw new AppException(ResultCode.NOAUTH);
        }

        return verify;
    }
}
